package com.ge.myoned.rabbitmq;

import cn.hutool.core.date.DateUtil;
import com.ge.myoned.config.RabbitMQConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author geqingxiang
 * @PackageName myProject
 * @Package com.ge.oned.rabbitmq
 * @Date 2023/6/7 17:53
 * @Version 1.0
 */
@Component
@Slf4j
public class MessageSender {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 使用死信队列发送消息方法封装
     * @param message
     * @param time
     */
    public void send(String message,Integer time){
        String ttl = String.valueOf(time*1000);
        //exchange和routingKey都为业务的就可以，只需要设置消息的过期时间
        rabbitTemplate.convertAndSend(RabbitMQConfig.DEMO_EXCHANGE, RabbitMQConfig.DEMO_ROUTEKEY,message, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //设置消息的过期时间，是以毫秒为单位的
                message.getMessageProperties().setExpiration(ttl);
                return message;
            }
        });
        log.info("使用死信队列消息:{}发送:{}发送成功,过期时间:{}秒。", DateUtil.now(),message,time);
    }
}
